<script setup>
import { ref } from 'vue'
import SockJS from 'sockjs-client'
import { Client } from '@stomp/stompjs'

const title = "后端->前端 有参"

const currentUser = ref(null)
const messages = ref([])
let stompClient = null

const connectAs = (userId) => {
  // 断开旧连接
  if (stompClient?.connected) {
    stompClient.deactivate()
    messages.value = []
  }

  // 建立新连接
  let url = `http://localhost:8080/ws?userId=${userId}`;
  console.log("建立连接：", url);
  const socket = new SockJS(url)
  stompClient = new Client({
    webSocketFactory: () => socket,
    debug: (str) => console.log(`STOMP调试：${str}`),
  })

  stompClient.onConnect = (frame) => {
    console.log("连接成功，帧头信息：", frame.headers);
    console.log("连接成功，帧头信息 stompClient：", stompClient);
    currentUser.value = userId
    const sub = stompClient.subscribe('/user/queue/messages', (message) => {
      console.log("收到原始消息:", message.body);
      try {
        const parsed = JSON.parse(message.body);
        messages.value = [parsed, ...messages.value.slice(0, 5)];
      } catch (e) {
        console.error("消息解析失败:", e);
      }
    })
    console.log("订阅对象：", sub);
  }

  stompClient.onStompError = (frame) => {
    console.error('协议错误:', frame.headers.message)
  }

  stompClient.onWebSocketClose = (event) => {
    console.warn("连接关闭：", event);
  }

  stompClient.activate()
}
</script>

<template>
  <h2>{{title}}</h2>
  <div class="user-box">
    <button @click="connectAs('user1')">以用户1连接</button>
    <button @click="connectAs('user2')">以用户2连接</button>
    <div v-if="currentUser" class="messages">
      <h3>{{ currentUser }} 的消息</h3>
      <div v-for="(msg, index) in messages" :key="index">
        {{ msg.time }} - {{ msg.content }}
      </div>
    </div>
  </div>
  <hr/>
</template>

<style scoped>
.user-box {
  padding: 20px;
  border: 1px solid #ccc;
  max-width: 500px;
  margin: 20px auto;
}

button {
  margin: 0 10px;
  padding: 8px 16px;
}
</style>
